import { asyncRouterMap, constantRouterMap } from '@/config/router.config'
import { clientId } from '@/config'
import axios from '@/utils/request'

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id)
  } else {
    return true
  }
}

// function filterAsyncRouter(routerMap, roles) {
//   const accessedRouters = routerMap.filter(route => {
//     roles.permissionList = roles.permissions.map(permission => { return permission.permissionId })
//     if (hasPermission(roles.permissionList, route)) {
//       if (route.children && route.children.length) {
//         route.children = filterAsyncRouter(route.children, roles)
//       }
//       return true
//     }
//     return false
//   })
//   return accessedRouters
// }
function hasRoutePermission() {}
function routePermissionsList(output, routePermissions) {
  routePermissions.forEach(p => {
    if (p.url) {
      output.push(p.raw.value)
    }
    if (p.children && p.children.length > 0) {
      routePermissionsList(output, p.children)
    }
  })
}
function filterAsyncRouter(routerMap, routePermissions) {
  return routerMap.filter(route => {
    if (routePermissions.indexOf(route.path)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, routePermissions)
      }
      return true
    }
    return false
  })
}

const permission = {
  state: {
    btnsPermission: [],
    routers: constantRouterMap,
    addRouters: [],
    hasSetRouters: false
  },
  getters: {
    btnPermission(state) {
      const list = sessionStorage.getItem('btnPermission')
      return list ? JSON.parse(list) : state.btnsPermission
    }
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
      state.hasSetRouters = true
    },
    SET_HAS_ROUTERS: (state, hasSet) => {
      state.hasSetRouters = hasSet
    },
    SET_BTNS: (state, btns) => {
      state.btnsPermission = btns
      sessionStorage.setItem('btnPermission', JSON.stringify(btns))
    }
  },
  actions: {
    // 获取按钮权限资源
    GetBtnResources({ commit }) {
      commit('SET_BTNS', []) // 获取前清理缓存
      let url = 'ycloud-authority/res/list-by-current-user?resType=2&clientId=' + clientId
      return axios.get(url).then(res => {
        const list = res.data || []
        commit('SET_BTNS', list)
      })
    },
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        // const roles = JSON.parse(localStorage.getItem("role"))
        const routePermissionsListOutput = []
        routePermissionsList(routePermissionsListOutput, data.res)
        const accessedRouters = filterAsyncRouter(asyncRouterMap, routePermissionsListOutput)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    },
    SetHasRouters({ commit }, data) {
      commit('SET_HAS_ROUTERS', data)
    }
  }
}

export default permission
